package org.example.rubbish.websocket;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import jakarta.websocket.*;
import jakarta.websocket.server.ServerEndpoint;
import org.example.rubbish.config.CorsServerEndpointConfigurator;
import org.example.rubbish.dto.AlarmDTO;
import org.example.rubbish.dto.WebSocketMessage;
import org.example.rubbish.service.AlarmService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@Component
@ServerEndpoint(value = "/websocket/alarm",
        configurator = CorsServerEndpointConfigurator.class)
public class WebSocketServer {

    private static final ConcurrentHashMap<String, OnlineUser> onlineUsers = new ConcurrentHashMap<>();
    private static final ConcurrentHashMap<String, Session> sessionMap = new ConcurrentHashMap<>();
    private static final ObjectMapper objectMapper = new ObjectMapper()
            .registerModule(new JavaTimeModule())  // ✅ 支持 Java 8 日期时间
            .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);  // ✅ 日期格式化为字符串

    private static AlarmService alarmService;

    // 使用Setter注入而不是字段注入
    @Autowired
    public void setAlarmService(AlarmService alarmService) {
        WebSocketServer.alarmService = alarmService;
    }

    @OnOpen
    public void onOpen(Session session) {
        String sessionId = session.getId();
        sessionMap.put(sessionId, session);

        /* ---------- 调试日志 ---------- */
        System.out.println("WebSocket连接建立，sessionId: " + sessionId);
        System.out.println("当前连接数: " + sessionMap.size());

        /* ---------- 解析查询参数 ---------- */
        Map<String, List<String>> params = session.getRequestParameterMap();
        String userId   = params.getOrDefault("userId",   List.of("")).get(0);
        String username = params.getOrDefault("username", List.of("")).get(0);
        String realName = params.getOrDefault("realName", List.of("")).get(0);

        if (!userId.isBlank()) {
            onlineUsers.put(userId, new OnlineUser(userId, username, realName));
            System.out.println("用户自动加入，userId: " + userId);
        }

        /* ---------- 给新会话发欢迎消息 ---------- */
        sendMessage(session, new WebSocketMessage("SYSTEM", "连接成功"));
        sendMessage(session, new WebSocketMessage("ONLINE_USERS", onlineUsers.values()));

        /* ---------- 广播最新连接数 ---------- */
        broadcastConnectionCount();
    }

    @OnClose
    public void onClose(Session session) {
        String sessionId = session.getId();
        sessionMap.remove(sessionId);

        /* ---------- 解析查询参数（OnClose 里仍然能拿到） ---------- */
        Map<String, List<String>> params = session.getRequestParameterMap();
        String userId = params.getOrDefault("userId", List.of("")).get(0);
        if (!userId.isBlank()) {
            onlineUsers.remove(userId);
            System.out.println("用户断开连接，移除 userId: " + userId);
        }

        System.out.println("WebSocket连接关闭，sessionId: " + sessionId);
        System.out.println("当前连接数: " + sessionMap.size());

        /* ---------- 广播最新连接数 ---------- */
        broadcastConnectionCount();
    }

    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        if ("ping".equals(message)) {
            session.getBasicRemote().sendText("pong");
            return;
        }
        try {
            System.out.println("【WebSocketServer】收到消息: " + message);
            // 1. 先尝试解析成统一实体
            WebSocketMessage msg = objectMapper.readValue(message, WebSocketMessage.class);
            System.out.println("【WebSocketServer】解析成功，type=" + msg.getType());
            String type = msg.getType();

            switch (type) {
                case "heartbeat":
                    sendMessage(session, new WebSocketMessage("heartbeat", "pong"));
                    break;

                case "acknowledge":
                    handleAcknowledgeMessage(msg, session);
                    break;

                case "ALARM":
                    handleAlarmMessage(msg, session);
                    break;

                case "USER_JOIN":          // ← 新增
                    handleUserJoin(msg, session);
                    break;

                default:
                    // 其他自定义业务
                    break;
            }
        } catch (Exception e) {
            // 2. 解析失败时兼容旧版 ping
            if ("PING".equalsIgnoreCase(message)) {
                sendMessage(session, new WebSocketMessage("pong", ""));
                return;
            }
            sendMessage(session, new WebSocketMessage("ERROR", "消息格式错误"));
        }
    }
    private void handleUserJoin(WebSocketMessage msg, Session session) {
        System.out.println("处理用户加入消息: " + msg);
        // 数据放在 msg.data（Map）里
        @SuppressWarnings("unchecked")
        Map<String,String> data = (Map<String,String>) msg.getData();

        String userId   = data.getOrDefault("userId", "");
        String username = data.getOrDefault("username", "");
        String realName = data.getOrDefault("realName", "");
        System.out.println("用户加入前在线用户数: " + onlineUsers.size());
        onlineUsers.put(userId, new OnlineUser(userId, username, realName));
        System.out.println("用户加入后在线用户数: " + onlineUsers.size());

        broadcastOnlineUsers();   // 广播最新列表
    }

    private void broadcastOnlineUsers() {
        System.out.println("准备广播在线用户，当前用户数: " + onlineUsers.size());
        System.out.println("用户列表: " + onlineUsers.values());
        // 统一使用 WebSocketMessage 格式
        WebSocketMessage message = new WebSocketMessage("ONLINE_USERS", onlineUsers.values());
        broadcastMessage(message);
    }
    // 此方法已废弃，统一使用 broadcastMessage
    @Deprecated
    private void broadcast(String json) {
        System.out.println(">>> 广播纯文本消息: " + json);
        for (Session s : sessionMap.values()) {
            if (s.isOpen()) {
                try {
                    s.getBasicRemote().sendText(json);
                    System.out.println(">>> 发送成功到 Session: " + s.getId());
                } catch (IOException e) {
                    System.err.println(">>> 发送失败到 Session: " + s.getId() + ", 错误: " + e.getMessage());
                }
            }
        }
    }
    private void handleAcknowledgeMessage(WebSocketMessage message, Session session) {
        try {
            Object data = message.getData();
            if (data instanceof java.util.Map) {
                java.util.Map<?, ?> dataMap = (java.util.Map<?, ?>) data;
                String alarmId = (String) dataMap.get("alarmId");
                String acknowledgedBy = (String) dataMap.get("acknowledgedBy");

                if (alarmId != null && acknowledgedBy != null && alarmService != null) {
                    boolean success = alarmService.acknowledgeAlarm(alarmId, acknowledgedBy);
                    if (success) {
                        sendMessage(session, new WebSocketMessage("ACKNOWLEDGE_RESULT", "报警确认成功"));
                    } else {
                        sendMessage(session, new WebSocketMessage("ACKNOWLEDGE_RESULT", "报警确认失败"));
                    }
                } else {
                    sendMessage(session, new WebSocketMessage("ERROR", "确认报警参数不完整"));
                }
            }
        } catch (Exception e) {
            sendMessage(session, new WebSocketMessage("ERROR", "处理确认消息失败"));
        }
    }

    private void handleAlarmMessage(WebSocketMessage message, Session session) {
        try {
            Object data = message.getData();
            AlarmDTO alarmDTO = null;

            if (data instanceof java.util.Map) {
                java.util.Map<?, ?> dataMap = (java.util.Map<?, ?>) data;
                alarmDTO = convertMapToAlarmDTO(dataMap);
            } else if (data instanceof AlarmDTO) {
                alarmDTO = (AlarmDTO) data;
            }

            if (alarmDTO != null && alarmService != null) {
                // 1. 保存到数据库
                alarmService.processNewAlarm(alarmDTO);

                // 2. 回复发送者
                sendMessage(session, new WebSocketMessage("ALARM_RESULT", "报警接收成功"));

                // 3. ✅ 广播给所有连接的客户端（包括报警页面）
                System.out.println(">>> 准备广播报警到所有客户端: " + alarmDTO.getAlarmId());
                broadcastAlarm(alarmDTO);

            } else {
                sendMessage(session, new WebSocketMessage("ERROR", "报警数据格式错误"));
            }
        } catch (Exception e) {
            System.err.println("!!! 处理报警消息失败: " + e.getMessage());
            e.printStackTrace();
            sendMessage(session, new WebSocketMessage("ERROR", "处理报警消息失败: " + e.getMessage()));
        }
    }

    private AlarmDTO convertMapToAlarmDTO(java.util.Map<?, ?> dataMap) {
        try {
            AlarmDTO alarmDTO = new AlarmDTO();

            if (dataMap.get("alarmId") != null) {
                alarmDTO.setAlarmId(dataMap.get("alarmId").toString());
            }
            if (dataMap.get("title") != null) {
                alarmDTO.setTitle(dataMap.get("title").toString());
            }
            if (dataMap.get("content") != null) {
                alarmDTO.setContent(dataMap.get("content").toString());
            }
            if (dataMap.get("source") != null) {
                alarmDTO.setSource(dataMap.get("source").toString());
            }
            if (dataMap.get("level") != null) {
                alarmDTO.setLevel(dataMap.get("level").toString());
            }
            if (dataMap.get("type") != null) {
                alarmDTO.setType(dataMap.get("type").toString());
            }

            if (dataMap.get("extraData") instanceof java.util.Map) {
                @SuppressWarnings("unchecked")
                java.util.Map<String, Object> extraData = (java.util.Map<String, Object>) dataMap.get("extraData");
                alarmDTO.setExtraData(extraData);
            }

            return alarmDTO;
        } catch (Exception e) {
            return null;
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        System.err.println("!!! WebSocket错误，sessionId: " + session.getId());
        System.err.println("!!! 错误详情: " + error.getMessage());
        error.printStackTrace();
    }

    private void sendMessage(Session session, WebSocketMessage msg) {
        if (session != null && session.isOpen()) {
            synchronized (session) {
                try {
                    session.getBasicRemote().sendText(objectMapper.writeValueAsString(msg));
                } catch (IOException e) {
                    System.out.println("单点消息发送失败: " + e.getMessage());
                }
            }
        }
    }


    public void broadcastAlarm(AlarmDTO alarmDTO) {
        System.out.println(">>> WebSocketServer 广播报警，当前在线会话数：" + sessionMap.size());
        WebSocketMessage message = new WebSocketMessage("ALARM", alarmDTO);
        broadcastMessage(message);
    }

    public void broadcastAcknowledgment(String alarmId, String acknowledgedBy) {
        WebSocketMessage message = new WebSocketMessage("ACKNOWLEDGMENT",
                new AcknowledgmentMessage(alarmId, acknowledgedBy));
        broadcastMessage(message);
    }

    public void broadcastSystemMessage(String systemMessage) {
        WebSocketMessage message = new WebSocketMessage("SYSTEM", systemMessage);
        broadcastMessage(message);
    }

    private void broadcastConnectionCount() {
        WebSocketMessage countMsg = new WebSocketMessage("STATS",
                Map.of("connectionCount", sessionMap.size(),
                        "onlineUsers",     onlineUsers.values()));
        broadcastMessage(countMsg);   // 复用你已有的 broadcastMessage 即可
    }

    private void broadcastMessage(WebSocketMessage message) {
        String messageJson;
        try {
            messageJson = objectMapper.writeValueAsString(message);
            System.out.println(">>> 准备广播消息，类型: " + message.getType() + ", JSON: " + messageJson);
        } catch (Exception e) {
            System.err.println("!!! 消息序列化失败: " + e.getMessage());
            e.printStackTrace();
            return;
        }

        int successCount = 0;
        int failCount = 0;

        for (Map.Entry<String, Session> entry : sessionMap.entrySet()) {
            String sessionId = entry.getKey();
            Session session = entry.getValue();

            try {
                if (session.isOpen()) {
                    synchronized (session) {
                        session.getBasicRemote().sendText(messageJson);
                        successCount++;
                        System.out.println(">>> 成功发送到 Session: " + sessionId);
                    }
                } else {
                    System.out.println(">>> Session已关闭，跳过: " + sessionId);
                }
            } catch (IOException e) {
                failCount++;
                System.err.println("!!! 发送失败到 Session: " + sessionId + ", 错误: " + e.getMessage());
                e.printStackTrace();
            }
        }

        System.out.println(">>> 广播完成 - 成功: " + successCount + ", 失败: " + failCount + ", 总会话数: " + sessionMap.size());
    }

    public int getConnectionCount() {
        return sessionMap.size();
    }

    private static class AcknowledgmentMessage {
        private String alarmId;
        private String acknowledgedBy;
        private long timestamp;

        public AcknowledgmentMessage() {
        }

        public AcknowledgmentMessage(String alarmId, String acknowledgedBy) {
            this.alarmId = alarmId;
            this.acknowledgedBy = acknowledgedBy;
            this.timestamp = System.currentTimeMillis();
        }

        public String getAlarmId() { return alarmId; }
        public void setAlarmId(String alarmId) { this.alarmId = alarmId; }
        public String getAcknowledgedBy() { return acknowledgedBy; }
        public void setAcknowledgedBy(String acknowledgedBy) { this.acknowledgedBy = acknowledgedBy; }
        public long getTimestamp() { return timestamp; }
        public void setTimestamp(long timestamp) { this.timestamp = timestamp; }
    }

    private static class StatsMessage {
        private int connectionCount;
        private long timestamp;

        public StatsMessage() {
        }

        public StatsMessage(int connectionCount) {
            this.connectionCount = connectionCount;
            this.timestamp = System.currentTimeMillis();
        }

        public int getConnectionCount() { return connectionCount; }
        public void setConnectionCount(int connectionCount) { this.connectionCount = connectionCount; }
        public long getTimestamp() { return timestamp; }
        public void setTimestamp(long timestamp) { this.timestamp = timestamp; }
    }
    public static class OnlineUser {
        private String userId;
        private String username;
        private String realName;

        public OnlineUser() {

        }

        public OnlineUser(String userId, String username, String realName) {
            this.userId = userId;
            this.username = username;
            this.realName = realName;
        }

        public String getUserId() {
            return userId;
        }

        public void setUserId(String userId) {
            this.userId = userId;
        }

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public String getRealName() {
            return realName;
        }

        public void setRealName(String realName) {
            this.realName = realName;
        }
    }

}
